package de.uni_mannheim;

import java.util.HashMap;
import java.util.Map;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class TeamStatsSaxHandler extends DefaultHandler {

	private Map<String, String> team1Stat;
	private Map<String, String> team2Stat;

	int currentTeam;

	@Override
	public void startDocument() {
		currentTeam = 0;
		team1Stat = new HashMap<String, String>();
		team2Stat = new HashMap<String, String>();
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

		if (qName.equalsIgnoreCase("team")) {
			currentTeam++;
		}

		String eventKey = attributes.getValue("event-key");
		if (qName.equalsIgnoreCase("event-metadata")) {
			team1Stat.put("event-key", eventKey);
			team2Stat.put("event-key", eventKey);
		}

		if (qName.equalsIgnoreCase("team-stats")) {
			getOtherTeamMap().put("opponentScore", attributes.getValue("score"));
		}

		for (String element : Converter.TEAM_STATS_ELEMENTS) {
			if (qName.equalsIgnoreCase(element)) {
				for (int i = 0; i < attributes.getLength(); i++) {
					String key = attributes.getQName(i);
					String value = attributes.getValue(i);
					getCurrentTeamMap().put(key, value);
				}
			}
		}
	}

	public Map<String, String> getCurrentTeamMap() {
		if (currentTeam == 1) {
			return team1Stat;
		} else if (currentTeam == 2) {
			return team2Stat;
		} else {
			throw new IllegalArgumentException("currentTeam value is wrong: " + currentTeam);
		}
	}

	public Map<String, String> getOtherTeamMap() {
		if (currentTeam == 1) {
			return team2Stat;
		} else if (currentTeam == 2) {
			return team1Stat;
		} else {
			throw new IllegalArgumentException("currentTeam value is wrong: " + currentTeam);
		}
	}

	public Map<String, String> getTeam1Stat() {
		return team1Stat;
	}

	public Map<String, String> getTeam2Stat() {
		return team2Stat;
	}

}
